package org.bigjava.novelplatform.common.handlerInterceptor;

import org.bigjava.novelplatform.common.enums.UserRole;
import org.bigjava.novelplatform.common.exception.UserActionException;
import org.bigjava.novelplatform.vo.UserInfoVo;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.bigjava.novelplatform.common.constant.NovelInfoConstant.SESSION_USER;
import static org.bigjava.novelplatform.common.exception.ExceptionCodeMessage.NOT_WRITER;

public class AdminHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            return true;
        }
        UserInfoVo UserInfo = (UserInfoVo) request.getSession().getAttribute(SESSION_USER);
        if (!UserInfo.getType().equalsIgnoreCase(UserRole.ADMIN.toString())) {
            throw new UserActionException(NOT_WRITER);
        }
        return true;
    }
}
